<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" size="small" style="width: 200px;" class="filter-item"
                placeholder="姓名、手机号"
                v-model="listQuery.keyword">
      </el-input>
      <el-button class="filter-item" type="primary" size="small" v-waves icon="search" @click="handleFilter">搜索
      </el-button>
      <el-button v-if="sys_user_add" size="small" class="filter-item" style="margin-left: 10px;" @click="handleCreate"
                 type="primary"
                 icon="edit">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" size="small" v-loading="listLoading" element-loading-text="加载中..." border fit
              highlight-current-row style="width: 99%">
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          <span>{{scope.row.userId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{scope.row.tel}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属部门" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.deptName}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色">
        <template slot-scope="scope">
          <span v-for="role in scope.row.roleNames">{{role}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱">
        <template slot-scope="scope">
          <span>{{scope.row.email}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="status-col" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.enable | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200" v-if="sys_user_edit">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="scope.row.enable" size="small" type="danger" @click="toggle(scope.row)">停用
          </el-button>
          <el-button v-if="!scope.row.enable" size="small" type="danger" @click="toggle(scope.row)">启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,30,50,100]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="序号" prop="userId" v-if="dialogStatus == 'update'">
          <el-input v-model="form.userId" placeholder="序号" :disabled=true></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="form.tel" placeholder="请输手机号" :disabled="dialogStatus=='update'"></el-input>
        </el-form-item>
        <el-form-item label="密码" placeholder="请输入密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select class="filter-item" v-model="form.deptId" placeholder="请选择" filterable :disabled="dialogStatus=='update'">
            <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.name" :value="item.deptId"
                       :disabled="!item.enable">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select class="filter-item" v-model="form.roleId" placeholder="请选择" filterable>
            <el-option v-for="item in rolesOptions" :key="item.roleId" :label="item.name" :value="item.roleId"
                       :disabled="!item.enable">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}{{ item.decription }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="phone">
          <el-input v-model="form.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enable">
          <el-select class="filter-item" v-model="form.enable" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item" :label="item | statusFilter" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">保存</el-button>
        <el-button v-else type="primary" @click="update('form')">更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {fetchList, getObj, addObj, putObj, toggleObj, fetchRole} from "@/api/user";
  import {fetchList as fetchDept} from "@/api/dept";
  import waves from "@/directive/waves/index.js"; // 水波纹指令
  import {mapGetters} from "vuex";
  import ElRadioGroup from "element-ui/packages/radio/src/radio-group";
  import ElOption from "element-ui/packages/select/src/option";

  export default {
    components: {
      ElOption,
      ElRadioGroup
    },
    name: "user",
    directives: {
      waves
    },
    data() {
      return {
        deptData: [],
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        form: {
          tel: undefined,
          password: undefined,
          deptId: undefined,
          roleId: undefined,
          email: undefined,
          enable: true
        },
        rules: {
          tel: [
            {
              required: true,
              message: "请输入手机号",
              trigger: "blur"
            },
            {
              min: 3,
              max: 20,
              message: "长度在 3 到 20 个字符",
              trigger: "blur"
            }
          ],
          password: [
            {
              required: false,
              message: "请输入密码",
              trigger: "blur"
            },
            {
              min: 6,
              max: 20,
              message: "长度在 6 到 20 个字符",
              trigger: "blur"
            }
          ],
          deptId: [
            {
              required: true,
              message: "请选择部门",
              trigger: "blur"
            }
          ],
          roleId: [
            {
              required: true,
              message: "请选择角色",
              trigger: "blur"
            }
          ],
          email: [
            {
              required: true,
              message: "邮箱",
              trigger: "blur"
            },
            {
              email: true,
              message: "格式错误",
              trigger: "blur"
            }
          ]
        },
        statusOptions: [true, false],
        deptOptions: [],
        rolesOptions: [],
        dialogFormVisible: false,
        sys_user_add: false,
        sys_user_edit: false,
        dialogStatus: "",
        textMap: {
          update: "编辑",
          create: "创建"
        },
        tableKey: 0
      };
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          true: "启用",
          false: "停用"
        };
        return statusMap[status];
      }
    },
    created() {
      this.getList();
      this.getFormData();
      this.sys_user_add = this.permissions["sys_user_add"];
      this.sys_user_edit = this.permissions["sys_user_edit"];
    },
    methods: {
      getList() {
        this.listLoading = true;
        this.listQuery.isAsc = false;
        fetchList(this.listQuery).then(response => {
          this.list = response.data.data.content;
          this.total = response.data.data.totalElements;
          this.listLoading = false;
        });
      },
      getFormData() {
        fetchRole().then(response => {
          this.rolesOptions = response.data.data;
        });
        fetchDept({page: 1, limit: 999}).then(response => {
          this.deptOptions = response.data.data.content;
        });
      },
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleCreate() {
        this.resetTemp();
        this.dialogStatus = "create";
        this.dialogFormVisible = true;
      },
      handleUpdate(row) {
        getObj(row.userId).then(response => {
          this.form = response.data.data;
          this.dialogFormVisible = true;
          this.dialogStatus = "update";
          this.form.roleId = response.data.data.roleIds[0];
        });
      },
      create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            addObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "创建成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
      },
      update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            this.dialogFormVisible = false;
            this.form.password = undefined;
            putObj(this.form).then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "修改成功",
                type: "success",
                duration: 2000
              });
            });
          } else {
            return false;
          }
        });
      },
      toggle(row) {
        toggleObj(row.userId, !row.enable)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "切换成功",
              type: "success",
              duration: 2000
            });
          });
      },
      resetTemp() {
        this.form = {
          id: undefined,
          tel: "",
          password: "",
          role: [],
          enable: true,
          deptId: "",
          email: ""
        };
      }
    }
  };
</script>
